import json
import time
from django.utils import timezone
from django.core.paginator import Paginator
from django.db import transaction
from django.db.models import Q
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from django.views import View
from django.http import JsonResponse
from django.views.decorators.cache import cache_page
from django.forms.models import model_to_dict

from app import models
from .models import FollowPrice ,SkuKeywords
# 缓存15分钟

'''
基础处理类，其他处理继承这个类
'''
class BaseView(View):
    '''
    检查指定的参数是否存在
    存在返回 True
    不存在返回 False
    '''
    def isExit(param):

        if (param == None) or (param == ''):
            return False
        else:
            return True

    '''
    转换分页查询信息
    '''
    def parasePage(pageIndex, pageSize, pageTotal, count, data):

        return {'pageIndex': pageIndex, 'pageSize': pageSize, 'pageTotal': pageTotal, 'count': count, 'data': data}

    '''
    转换分页查询信息
    '''
    def parasePage(pageIndex, pageSize, pageTotal, count, data):
        return {'pageIndex': pageIndex, 'pageSize': pageSize, 'pageTotal': pageTotal, 'count': count, 'data': data}

    '''
    成功响应信息
    '''
    def success(msg='处理成功'):
        resl = {'code': 0, 'msg': msg}
        return HttpResponse(json.dumps(resl), content_type='application/json; charset=utf-8')

    '''
    成功响应信息, 携带数据
    '''
    def successData(data, msg='处理成功'):
        resl = {'code': 0, 'msg': msg, 'data': data}
        return HttpResponse(json.dumps(resl), content_type='application/json; charset=utf-8')

    '''
    系统警告信息
    '''
    def warn(msg='操作异常，请重试'):
        resl = {'code': 1, 'msg': msg}
        return HttpResponse(json.dumps(resl), content_type='application/json; charset=utf-8')

    '''
    系统异常信息
    '''
    def error(msg='系统异常'):
        resl = {'code': 2, 'msg': msg}
        return HttpResponse(json.dumps(resl), content_type='application/json; charset=utf-8')



class FollowPriceView(BaseView):

    def get_FollowPrice_data(self, request, module):
        """
        获取FollowPrice符合条件的数据列表，这里可添加具体的筛选条件。
        """
        is_leader = hasattr(request.user, 'userprofile') and request.user.userprofile.is_leader

        storename2 = request.GET.get('storename2')
        keywords = request.GET.get('keywords2')
        chargeman = request.GET.get('chargeman2')
        ebay = request.GET.get('ebay2')
        ali = request.GET.get('ali2')
        followstatus = request.GET.get('follow_other_status2')
        conditions = Q()
        intnocondition = 1
        iebay = 0
        iali = 0
       
        if ebay == 'true':
            iebay = 1
        if ali == 'true':
            iali = 1
        if not is_leader:
            conditions &= Q(username=request.user.username,
                            username__isnull=False)
        # 构建title相关条件
        if storename2:
            conditions &= Q(storename__icontains=storename2.strip(),
                            storename__isnull=False)
            intnocondition = 0

        # 构建author相关条件
        if keywords:
            conditions &= Q(keywords__icontains=keywords.strip(),
                            keywords__isnull=False)
            intnocondition = 0

        # 构建date相关条件
        if chargeman:
            conditions &= Q(username__icontains=chargeman.strip(),
                            username__isnull=False)
            intnocondition = 0

        if iebay == 1:
            conditions &= Q(shop_type__exact='ebay', shop_type__isnull=False)
            intnocondition = 0

        if iali == 1:
            conditions &= Q(shop_type__exact='ali', shop_type__isnull=False)
            intnocondition = 0

        # 构建date相关条件
        if followstatus and followstatus != '是否跟价':
            if followstatus == '已跟价':
                conditions &= Q(itemid__isnull=False) & Q(itemid__regex=r'.{3,}')

                intnocondition = 0  
            if followstatus == '未跟价':
                conditions &= (Q(itemid__isnull=True) | Q(itemid='') | Q(itemid__regex=r'^.{0,2}$'))
                intnocondition = 0  

        FollowPricedata = FollowPrice.objects.filter(conditions)
           
        if intnocondition == 1:
            FollowPricedata = FollowPrice.objects.all()
        return FollowPricedata

    def get_SkuKeywords_data(self, request, module):
        """
        获取SkuKeywords符合条件的数据列表，同样可按需添加筛选条件。
        """
        
        is_leader = hasattr(request.user, 'userprofile') and request.user.userprofile.is_leader

        storename2 = request.GET.get('storename2')
        keywords = request.GET.get('keywords2')
        chargeman = request.GET.get('chargeman2')
        ebay = request.GET.get('ebay2')
        ali = request.GET.get('ali2')
        followstatus = request.GET.get('follow_other_status2')
        conditions = Q()
        intnocondition = 1
        iebay = 0
        iali = 0
       
        if ebay == 'true':
            iebay = 1
        if ali == 'true':
            iali = 1
        if not is_leader:
            conditions &= Q(username=request.user.username,
                            username__isnull=False)
        # 构建title相关条件
         
        # 构建author相关条件
        # if keywords:
        #     conditions &=  Q(keywords__icontains=keywords.strip(),
        #                     keywords__isnull=False)
        #     intnocondition = 0

        # 构建date相关条件
        if chargeman:
            conditions &= Q(username__icontains=chargeman.strip(),
                            username__isnull=False)
            intnocondition = 0

        if iebay == 1:
            conditions &= Q(ebay__exact=iebay)
            intnocondition = 0

        if iali == 1:
            conditions &= Q(ali__exact=iali)
            intnocondition = 0

        # 构建date相关条件
        # if followstatus and followstatus != '是否跟价':
        #     conditions &= Q(followstatus__contains=followstatus,
        #                     followstatus__isnull=False)
        #     intnocondition = 0

        queryset = SkuKeywords.objects.filter(conditions)
        if intnocondition == 1:
            queryset = SkuKeywords.objects.all()
        return queryset

    def submit_followprice_data(self, request, module):
        """
        获取SkuKeywords符合条件的数据列表，同样可按需添加筛选条件。
        """
        data_str = request.GET.get(
            'data')  # 从GET请求的查询参数中获取名为'data'的参数值（前端传来的JSON字符串数据）
        received_data = json.loads(data_str)  # 解析JSON字符串为Python的二维数组对象
        sku = ""
        try:
            with transaction.atomic():  # 使用事务保证数据一致性
                for row in received_data:
                    followprice = FollowPrice.objects.filter(id=row[0])
                    sku = row[1]
                    for f1 in followprice:
                        f1.itemid = row[1]
                        # f1.lowvalue = row[2]
                        # f1.followstatus = '已跟价'
                        # if f1.lowvalue=='':
                        #     f1.lowvalue=0
                        # f1.opdate = timezone.now()  # 设置opdate字段为当前时间
                        # if not row[1] or len(row[1]) < 5:
                        #     f1.followstatus = '未跟价'
                        #     continue
                        f1.save()

                # for row in received_data:
                #     followprice = FollowPrice.objects.filter(id=row[0])
                #     sku = row[1]
                #     if not sku or sku=='':
                #         continue    
                #     skukeywords = SkuKeywords.objects.filter(sku=sku)
                #     for f2 in skukeywords:
                #         f2.followstatus = '已跟价'
                #         f2.save()
            return JsonResponse({'message': '数据接收成功'}, status=200)
        except Exception as e:
            print(e)
            return JsonResponse({'message': '数据接收失败'}, status=500)

    def changelist_view(self, request, module):
        """
        重写默认的列表视图展示逻辑
        """
        # 获取原始数据
       

        if module == 'query0':
            SkuKeywords_data = self.get_SkuKeywords_data(request, module)
            data = list(SkuKeywords_data.values()
                        )  # 使用values方法将QuerySet转换为包含字典的列表，每个字典代表一条记录的部分字段信息

            context = {'SkuKeywords': SkuKeywords_data, 'FollowPrice': []}

            return JsonResponse(data, safe=False)

        if module == 'query1':
            page = request.GET.get('page', 1)
            page_size = request.GET.get('pagesize', 20)
            
            try:
                page = int(page)
                page_size = int(page_size)
            except (TypeError, ValueError):
                page = 1
                page_size = 20
            queryset = self.get_FollowPrice_data(request, module)
            paginator = Paginator(queryset, page_size)
            if page>paginator.num_pages:
                page=paginator.num_pages
            if page<1:
                page=1
            current_page=None
            try:
                current_page = paginator.page(page)
                FollowPrice_data = current_page.object_list
            except Exception as e:
                current_page = paginator.page(paginator.num_pages)
                FollowPrice_data = []

            # data = list(FollowPrice_data.values())
            page0=page
        
            SkuKeywords_data = self.get_SkuKeywords_data(request, module)
            data0 = list(SkuKeywords_data.values()
                        )  # 使用values方法将QuerySet转换为包含字典的列表，每个字典代表一条记录的部分字段信息
            paginator0 = Paginator(data0, page_size)

            try:
                if page0>paginator0.num_pages :
                    page0=paginator0.num_pages  
                if page0<1:
                    page0=1
                current_page0 = paginator0.page(page0)
                SkuKeywords_data = [
                    {
                        'sku': item.get('sku', ''),
                        'id': item.get('id', ''),
                        'keywords': item.get('keywords', ''),
                        'lowvalue': item.get('lowvalue', ''),
                        'ebay': item.get('ebay', ''),
                        'ali': item.get('ali', ''),
                        'followstatus': item.get('followstatus', '')
                    }
                    for item in current_page0.object_list
                    ]
            except Exception as e:
                current_page0 = paginator0.page(paginator0.num_pages)
                SkuKeywords_data = []

            context = {'SkuKeywords': SkuKeywords_data, 'FollowPrice': []}
            data = {  
            'FollowPrice': list(current_page.object_list),
            'SkuKeywords': SkuKeywords_data,
            'pagination': {'current_page': page, 'total_pages': paginator.num_pages, 'total_items': paginator.count, 'page_size': page_size, 'has_next': current_page.has_next(), 'has_previous': current_page.has_previous()}
            }
        if module == 'querysubmit':
            return self.submit_followprice_data(request, module)
        if module == 'queryexport':
            return self.export_excel(request, module)
        try:
            if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
                    # AJAX 请求返回 JSON
                    # data = self.changelist_view(request, module)
                json_data = {
                        'status': 'success',
                        'data': {
                            'pagination': data['pagination'],
                            'FollowPrice': [model_to_dict(item) for item in data['FollowPrice']],  # 使用 model_to_dict 转换
                            'SkuKeywords': data.get('SkuKeywords', [])
                        }
                        }
                
                print('Pagination:', json_data['data']['pagination'])
                
                print(data['FollowPrice'])
                return JsonResponse(json_data, safe=False)
            else:
                    # 普通请求返回页面
                    # data = self.changelist_view(request, module)
                return render(request, 'FollowPrice2.html', data)
        except Exception as e:
            print(f"Error in render function: {e}")
            return HttpResponse(f"Error in rendering template: {e}",
                                status=500)

    def export_excel(self, request, module):
        # 创建一个新的Excel工作簿
        wb = Workbook()
        # 获取活动的工作表（默认会有一个Sheet1）
        ws = wb.active
        ws.title = "书籍数据"  # 这里可以��据实际需求自定义工作表的主标题

        # 获取模型的字段，以字段的verbose_name作为表头
        model_fields = FollowPrice._meta.fields
        headers = [field.verbose_name for field in model_fields]
        ws.append(headers)

        # 从数据库中获取数据并写入Excel表格
        fls = FollowPrice.objects.all()
        for book in fls:
            data_row = []
            for field in model_fields:
                field_value = getattr(book, field.name)
                if isinstance(field_value, datetime.date):
                    field_value = field_value.strftime('%Y-%m-%d')
                elif isinstance(field_value, bool):
                    field_value = "是" if field_value else "否"
                elif field_value is None:
                    field_value = ""
                data_row.append(field_value)
            ws.append(data_row)

        # 创建HttpResponse对象，设置响应内容类型为Excel文件类型
        response = HttpResponse(
            content_type=
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        )
        response[
            'Content-Disposition'] = 'attachment; filename="books_data.xlsx"'

        # 将工作簿内容保存到响应对象中
        wb.save(response)
        return response

    def get(self, request, module, *args, **kwargs):
        return self.changelist_view(request, module)
        if module == 'login':
            return render(request, 'login.html')

        elif module == 'exit':

            del request.session["user"]
            del request.session["type"]

            return HttpResponseRedirect('/jobs/login')

        if module == 'info':

            return SysView.getSessionInfo(request)

        elif module == 'show':

            return render(request, 'index.html')

        elif module == 'sysNum':

            return SysView.getSysNums(request)

    def post(self, request, module, *args, **kwargs):

        if module == 'login':

            return SysView.login(request)

        if module == 'info':
            return SysView.updSessionInfo(request)

        if module == 'pwd':
            return SysView.updSessionPwd(request)

    def login(request):

        userName = request.POST.get('userName')
        passWord = request.POST.get('passWord')

        user = models.Users.objects.filter(userName=userName)

        if (user.exists()):

            user = user.first()
            if user.passWord == passWord:
                request.session["user"] = user.id
                request.session["type"] = user.type

                return SysView.success()
            else:
                return SysView.warn('用户密码输入错误')
        else:
            return SysView.warn('用户名输入错误')

    def getSessionInfo(request):

        user = request.session.get('user')

        data = models.Users.objects.filter(id=user)

        resl = {}
        for item in data:
            resl = {
                'id': item.id,
                'userName': item.userName,
                'passWord': item.passWord,
                'gender': item.gender,
                'name': item.name,
                'age': item.age,
                'phone': item.phone,
                'type': item.type,
            }

        return SysView.successData(resl)

    def getSysNums(request):

        resl = {
            'companiesTotal': models.Companies.objects.all().count(),
            'jobTotal': models.Jobs.objects.all().count(),
            'inStuTotal': models.Students.objects.filter(status=0).count(),
            'outStuTotal': models.Students.objects.filter(status=1).count()
        }

        return BaseView.successData(resl)

    def updSessionInfo(request):

        user = request.session.get('user')

        models.Users.objects.filter(id=user).update(
            userName=request.POST.get('userName'),
            name=request.POST.get('name'),
            age=request.POST.get('age'),
            gender=request.POST.get('gender'),
            phone=request.POST.get('phone'),
        )

        return SysView.success()

    def updSessionPwd(request):

        user = request.session.get('user')

        models.Users.objects.filter(id=user).update(
            passWord=request.POST.get('password'), )

        return SysView.success()

 
